import tkinter as tk
from PIL import Image, ImageTk,ImageGrab
import os
import time

# 鼠标按下
def on_mouse_down(event):
    # 当鼠标按下时，开始绘图
    canvas.old_x = event.x
    canvas.old_y = event.y

# 鼠标移动
def on_mouse_move(event):
    # 当鼠标移动时，根据鼠标位置绘制线条
    if canvas.old_x and canvas.old_y:
        canvas.create_line(canvas.old_x, canvas.old_y, event.x, event.y, width=2)
        canvas.old_x = event.x
        canvas.old_y = event.y

# 鼠标抬起
def on_mouse_up(event):
    # 当鼠标释放时，停止绘图
    canvas.old_x = None
    canvas.old_y = None

# 清空画布，默认为白色
def clear_canvas():
    canvas.delete("all")
    canvas.create_rectangle(0, 0, w, h, fill="white")

# 保存图像信息到数组中
def save_image():
    # 标注的文字
    txt = font_entry.get()
    if txt!= '':
        # 保存画布内容(需要捕获canvas的四个坐标点)
        x = root.winfo_rootx() + canvas.winfo_x()
        y = root.winfo_rooty() + canvas.winfo_y()
        x1 = x + canvas.winfo_width()
        y1 = y + canvas.winfo_height()
        image = ImageGrab.grab((x, y, x1, y1))
        path = '3/2/'+ txt + '/'
        # 创建文件夹(不建议使用汉字)
        if not os.path.exists(path):
            # 不存在就创建文件夹
            os.makedirs(path)
        # 用时间当文件名（秒）
        name = str(int(time.time()))
        file = path + name + ".png"
        print(file)
        image.save(file)
        # 追加文件名
        if txt in pngs:
            pngs[txt].append(file)
        else:
            pngs[txt] = [file]
    else:
        word.config(text="请输入标注的文字")
        font_entry.focus()
# 缩放至统一大小
def scale_images():
    # 对所有图片进行缩放
    for dir in pngs:
        for file in pngs[dir]:
            image = Image.open(file)
            image = image.resize((size, size))
            photo = ImageTk.PhotoImage(image)
            # 显示图片
            label = tk.Label(imgs_frame, image=photo)
            label.image = photo
            label.pack(side=tk.LEFT)

# 创建主窗口
root = tk.Tk()
root.title("手写体抠图")
root.geometry("200x300")

# 初始化数据
w = 200
h = 200
size = 16
# 保存图像为字符串
pngs = {}
# 创建画布
canvas = tk.Canvas(root, width=w, height=h, bg="white")
canvas.pack()

# 绑定鼠标事件
canvas.bind("<Button-1>", on_mouse_down)
canvas.bind("<B1-Motion>", on_mouse_move)
canvas.bind("<ButtonRelease-1>", on_mouse_up)

# 初始化变量
canvas.old_x = None
canvas.old_y = None

frame= tk.Frame()
frame.pack()
tk.Button(frame, text="清空", command=clear_canvas).pack(side=tk.LEFT)
word = tk.Label(frame, text="标注的文字：")
word.pack(side=tk.LEFT)
font_entry = tk.Entry(frame, width=2)
font_entry.pack(side=tk.LEFT)

tk.Button(frame, text="保存", command=save_image).pack(side=tk.LEFT)

tk.Button(root, text="全部缩放至统一大小", command=scale_images).pack()
imgs_frame = tk.Frame(root)
imgs_frame.pack()


# 是否准备好
ready = False
# 运行主循环
root.mainloop()